import request from '../utils/request.js'


function prepareData(list, simple = true) {
  let map = {}
  list.forEach(it => {
    if (map[it.parent_id]) {
      map[it.parent_id].push({ ...it, value: it.region_id, label: it.region_name })
    } else {
      map[it.parent_id] = [{ ...it, value: it.region_id, label: it.region_name }]
    }
  })
  return setChild(map[0], map, simple)
}

function setChild(list = [], map, simple = true) {
  list.forEach(it => {
    if (map[it.region_id]) {
      it.children = map[it.region_id]
      !simple && it.children && it.children.length && setChild(it.children, map, simple)
    }
  })
  return list
}

export async function fetchRegion(simple = true) {
  const { list } = await request(
    {
      url: '/api/halo-dashboard/v1/region'
    },
    false
  )
  const regionData = prepareData(list, simple)

  return {regionData,originData:list}
}